package com.chat.datea.acitivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chat.datea.R;
import com.chat.datea.service.MusicInterface;
import com.chat.datea.service.MusicService;
import com.chat.datea.service.UpdateService;
import com.chat.datea.utils.exitapplication.ExitApplication;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Shura on 15/11/2.
 */

public class SettingActivity extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private CheckBox receive_push;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private ImageView setting_back;
    private CardView exit;
    private TextView download_directory, clean_cache, account_bind, feedback, rating, share, update_detection, about;
    private Intent it;
    private static MusicInterface mi;
    private MyServiceConn conn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        it = new Intent(this, MusicService.class);
        conn = new MyServiceConn();
        bindService(it, conn, BIND_AUTO_CREATE);
        setContentView(R.layout.activity_setting);
        ExitApplication.getInstance().addActivity(this);
        getLocalVersion();

        sharedPreferences = getSharedPreferences("push", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        setting_back = (ImageView) findViewById(R.id.setting_back);
        receive_push = (CheckBox) findViewById(R.id.receive_push);
        download_directory = (TextView) findViewById(R.id.download_directory);
        clean_cache = (TextView) findViewById(R.id.clean_cache);
        account_bind = (TextView) findViewById(R.id.account_bind);
        feedback = (TextView) findViewById(R.id.feedback);
        rating = (TextView) findViewById(R.id.rating);
        share = (TextView) findViewById(R.id.share);
        update_detection = (TextView) findViewById(R.id.update_detection);
        about = (TextView) findViewById(R.id.about);
        exit = (CardView) findViewById(R.id.exit);

        receive_push.setOnCheckedChangeListener(this);
        setting_back.setOnClickListener(this);
        download_directory.setOnClickListener(this);
        clean_cache.setOnClickListener(this);
        account_bind.setOnClickListener(this);
        feedback.setOnClickListener(this);
        rating.setOnClickListener(this);
        share.setOnClickListener(this);
        update_detection.setOnClickListener(this);
        about.setOnClickListener(this);
        exit.setOnClickListener(this);
    }

    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.clean_cache:
                executeCacheClear();
                Toast.makeText(this, "清理缓存", Toast.LENGTH_LONG).show();
                break;
            case R.id.exit:
                mi.go();
                stopService(it);

                ExitApplication.getInstance().exit();
                break;
            case R.id.feedback:
                Intent intent = new Intent(this, FeedbackActivity.class);
                startActivity(intent);
                break;
            case R.id.rating:
                // 跳转到应用市场，通过包名获取应用信息
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent1);
                break;
            case R.id.share:
                // 跳转到分享页面
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setType("text/*");
                // 添加分享内容
//                sendIntent.putExtra(Intent.EXTRA_TEXT, contentEditText.getText().toString());
                startActivity(sendIntent);
                break;
            case R.id.about:
                Intent intent2 = new Intent(this, AboutActivity.class);
                startActivity(intent2);
                break;
            case R.id.update_detection:
                getLocalVersion();
                getServiceVersion();
                updateVersion(v);
                break;
        }
    }

    /**
     * 获取本地版本号
     */
    public int getLocalVersion() {
        int localVersion = 0;
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            localVersion = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 获取服务器版本号
     */
    public int getServiceVersion() {
        int serviceVersion = 183;
        return serviceVersion;
    }

    /**
     * 版本更新
     */
    public void updateVersion(View v) {
        if (getServiceVersion() > getLocalVersion()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
            builder.setTitle("检查到新版本");
            builder.setMessage("是否更新");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startService(new Intent(SettingActivity.this, UpdateService.class));
                }
            });
            builder.create().show();
        }
    }

    /**
     * 调用Method清除缓存的方法
     */
    public void executeCacheClear() {
        PackageManager packageManager = this.getApplicationContext().getPackageManager();
        // 得到PackageManager的所有方法
        Method[] methods = packageManager.getClass().getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals("freeStorageAndNotify")) {
                // 找到要使用的方法
                try {
                    m.invoke(packageManager, Long.MAX_VALUE, null);
                } catch (Exception e) {
                    // 方法调用失败，可能是权限问题
                }
                break;

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked == false) {
            Set<Integer> days = new HashSet<>();
            JPushInterface.setPushTime(getApplicationContext(), days, 0, 0);
            editor.putBoolean("push", false);
            editor.commit();
            Toast.makeText(SettingActivity.this, "关闭推送", Toast.LENGTH_LONG).show();
        } else {
            Set<Integer> days = new HashSet<>();
            days.add(0);
            days.add(1);
            days.add(2);
            days.add(3);
            days.add(4);
            days.add(5);
            days.add(6);
            JPushInterface.setPushTime(getApplicationContext(), days, 0, 23);
            editor.putBoolean("push", true);
            editor.commit();
            Toast.makeText(SettingActivity.this, "接收推送", Toast.LENGTH_LONG).show();
        }
    }
}
